/*
 * ap管理类
 */
package com.rainfull.core;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;  

import com.rainfull.util.json.HTTP;
import com.rainfull.util.json.JSONArray;
import com.rainfull.util.json.JSONException;
import com.rainfull.util.HttpUtil;
import com.rainfull.util.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;  
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;  
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;  

public class RAPMgr extends BroadcastReceiver
{  
		//定义WifiManager对象  
	   public WifiManager m_wifiManager = null;  
	   //上下文
	   private Context m_contex = null;
	   private IRUIAPNotify m_wifiNotify = null;
	   private List<ScanResult> m_wifiList = null;
	   //构造器  
	   public RAPMgr(Context context, IRUIAPNotify wifiNotify)  
	   {  
		   m_wifiNotify = wifiNotify;
		   m_contex = context;
		   //取得WifiManager对象  
		   m_wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		   init();
	   }
	   private void init()
	   {
		   //监听wifi状态变化intent
		   m_contex.registerReceiver(this, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
		   //监听wifi扫描结果state
		   m_contex.registerReceiver(this, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		 //监听wifi扫描结果state
		   m_contex.registerReceiver(this, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
		   
	       //取得WifiInfo对象  
	       //mWifiInfo = m_wifiManager.getConnectionInfo();  
	   }
	   
	   /*
	    * 获取当前连接信息
	    */
	   public WifiInfo getCurrConn()
	   {
		   return m_wifiManager.getConnectionInfo();
	   }
	   /*
	    * Ap连接
	    
	   public  boolean connAp(String strBSSID, String strPwd)
	   {
		   WifiConfiguration wc = new WifiConfiguration();
		   wc.SSID = "\"coolboy\"";
		   wc.BSSID = "\""+strBSSID+"\"";
		   wc.preSharedKey  = "\""+strPwd+"\"";
		   wc.hiddenSSID = true;
		   wc.status = WifiConfiguration.Status.ENABLED;        
		   wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		   wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		   wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		   wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
		   wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
		   wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
		   int res = m_wifiManager.addNetwork(wc);
		   boolean b = m_wifiManager.enableNetwork(res, true);      
           return true;
	   }
	  */
	   public String getCfgPwdByNetWorkId(int nId)
	   {
		   	String strPwd = "";
		   	WifiConfiguration wifiCfg = getConnConfigInfoByNetWorkId(nId);            		
			if (wifiCfg != null)
			{
				//todo获取密码的方式可能要修改
				strPwd = wifiCfg.preSharedKey;
				if (strPwd == null)
				{
					strPwd = wifiCfg.wepKeys[0];
				}			
				if (strPwd == null)
					strPwd = "";
				if (strPwd.length() > 1 &&
					strPwd.charAt(0) == '\"' && 
					strPwd.charAt(strPwd.length() - 1) == '\"')
				{
					strPwd = strPwd.substring(1, strPwd.length() - 1);
				}
			}
			return strPwd;
	   }
	  
	   /*
	    * 连接到某一个AP
	    */
	   public boolean ConnToAp(ScanResult scanResult, String strPwd)
	   {
		   List<WifiConfiguration> listConfig = getConnConfigInfoByBSSID(scanResult.BSSID);
		   boolean bRet = false;
		   if (listConfig.size() > 0)
		   {			   
			   for (int i = 0; i < listConfig.size(); i++)
			   {				 				   
				   bRet = WifiHelper.changePasswordAndConnect(m_wifiManager, listConfig.get(i), 
						   									  strPwd, 100);
				   if (bRet == true)
				   {
					   break;
				   }
			   }
		   }
		   if (bRet == false)
		   {
			   bRet = WifiHelper.connectToNewNetwork(m_wifiManager, scanResult, strPwd, 100);
		   }
		   return bRet;
	   }
	   @Override
	   public void onReceive(Context contex, Intent intent) 
	   {
		   String strAction = intent.getAction();
			//wifi状态发生变化
			if (strAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
			{
				//wifi状态发送变化
				m_wifiNotify.onWifiStateChanged(getWifiState());
			}
			else if (strAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
			{
				//wifi结果扫描完成
				m_wifiList = m_wifiManager.getScanResults();
				m_wifiNotify.onScanResult(m_wifiList);
			}
			else if (strAction.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
			{				
		        final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
		        String strBSSID = intent.getStringExtra(WifiManager.EXTRA_BSSID);
		        if (strBSSID == null)
		        	strBSSID = "";
		        //WifiInfo wifiInfo = getCurrConn();
		        //String strBSSID = "";
		        //if (wifiInfo != null)
		        //	strBSSID = wifiInfo.getBSSID();
                m_wifiNotify.onApConnStateChange(networkInfo, strBSSID);            
			}
			
	   }
	   //扫描附近的ap热点
	   public void scanAp()
	   {
		   boolean bRet = m_wifiManager.startScan();
	   }
	   
	   //获取wifi状态
	   public int getWifiState()  
	   { 
		   return m_wifiManager.getWifiState();
	   } 
	   
	   public WifiInfo getConnConfigInfo()  
	   { 
		   WifiInfo info = m_wifiManager.getConnectionInfo();
		   return info;   		   
	   }
	   
	   public WifiConfiguration getConnConfigInfoByNetWorkId(int nId)  
	   {
		   List<WifiConfiguration> listCfg = m_wifiManager.getConfiguredNetworks();
		   int nNetWorkId = -1;
		   for (int i = 0; i < listCfg.size(); i++)
		   {
			   
			   nNetWorkId = listCfg.get(i).networkId;
			   if (nNetWorkId == nId)
			   {
				   return listCfg.get(i);
			   }
		   }
		   return null;
	   }
	   
	   public List<WifiConfiguration> getConnConfigInfoByBSSID(String strBSSID)  
	   {
		   List<WifiConfiguration> listCfgOut = new ArrayList<WifiConfiguration>(); 
		   List<WifiConfiguration> listCfg = m_wifiManager.getConfiguredNetworks();
		   String strBSSIDInfo = "";
		   for (int i = 0; i < listCfg.size(); i++)
		   {
			   
			   strBSSIDInfo = listCfg.get(i).BSSID;
			   if (strBSSIDInfo != null && strBSSIDInfo.length() != 0 && strBSSIDInfo.equals(strBSSID))
			   {
				   listCfgOut.add(listCfg.get(i));
			   }
		   }
		   return listCfgOut;
	   }	   
	   //设置wifi状态
	   public void setWifiState(boolean bEnable)  
	   {  
		   int wifiState = getWifiState();
		   if((wifiState == WifiManager.WIFI_STATE_ENABLED || 
			wifiState == WifiManager.WIFI_STATE_ENABLING) && 
			bEnable == false) 
		   {			   
			   m_wifiManager.setWifiEnabled(false);
		   }
		   if((wifiState == WifiManager.WIFI_STATE_DISABLED || 
			wifiState == WifiManager.WIFI_STATE_DISABLING) && 
			bEnable == true) 
		   {			   
			   m_wifiManager.setWifiEnabled(true);
		   }			   
	   }
	   /*
	    * 获取手机的imei号
	    */
	   public String getImei()
	   {
		   String strImei = "";
		   strImei = ((TelephonyManager)m_contex.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		   if (strImei == null)
			   return "";
		   else
			   return strImei;
	   }
	   
}  